﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsSpeech
{
    /// <summary>
    /// 文本转语音并保存wav和MP3文件
    /// </summary>
    public class MySpeech
    {
        VoiceClass _setViceClass;
        public MySpeech(VoiceClass setViceClass)
        {
            _setViceClass = setViceClass;
        }
        private SpeechSynthesizer synth = null;
        /// <summary>
        /// 返回一个SpeechSynthesizer对象
        /// </summary>
        /// <returns></returns>
        private SpeechSynthesizer GetSpeechSynthesizerInstance()
        {
            if (synth == null)
            {
                synth = new SpeechSynthesizer();
            }
            return synth;
        }
        /// <summary>
        /// 开始朗读 放在线程中
        /// </summary>
        /// <param name="VoiceObject"></param>
        private void RingVoice(object VoiceObject)
        {
            try
            {
                VoiceClass voiceClass = (VoiceClass)VoiceObject;
                synth = GetSpeechSynthesizerInstance();
                //synth.SelectVoice(voiceClass.VoiceName);
                if (_setViceClass.Rate > 0)
                    synth.Rate = _setViceClass.Rate;
                if (_setViceClass.Volume > 0)
                    synth.Volume = _setViceClass.Volume;

                synth.SpeakAsync(voiceClass.VoiceText);
            }
            catch (Exception er)
            {
                Console.WriteLine(er.ToString());
            }
        }
        /// <summary>
        ///  播放
        /// </summary>
        public void Play()
        {
            Thread thread = new Thread(RingVoice);
            thread.Start(_setViceClass);
        }
        public void SaveMp3()
        {
            try
            {
                synth = GetSpeechSynthesizerInstance();

                //synth.SelectVoice(_setViceClass.VoiceName);
                if (_setViceClass.Rate > 0)
                    synth.Rate = _setViceClass.Rate;
                if (_setViceClass.Volume > 0)
                    synth.Volume = _setViceClass.Volume;

                string wavfileName = "";
                if (_setViceClass.VoiceText.Length > 20)
                {
                    wavfileName = DateTime.Now.ToFileTime().ToString();
                }
                else
                {
                    wavfileName = _setViceClass.VoiceText;
                }
                string str = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + wavfileName + ".wav";
                
                synth.SetOutputToWaveFile(str);
                synth.Speak(_setViceClass.VoiceText);
                synth.SetOutputToNull();
            }
            catch (Exception er)
            {
                Console.WriteLine(er.ToString());
            }
        }
    }
}
